module Apiable
  extend ActiveSupport::Concern

  included do
    skip_before_action :verify_authenticity_token
    before_action :set_access, :api_signed_in
    skip_before_action :api_signed_in, only: [:new_session]

    # Handling Error
    rescue_from Exception do |e|
      error! "there is something wrong!"
      logger.error e.message
      logger.error e.backtrace.join("\n")
    end
  end

  private
    def set_access
      response.headers["Access-Control-Allow-Origin"] = "*"
      response.headers["Access-Control-Allow-Credentials"] = "true"
    end

    def api_authentication_token_valid?
      if params[:token].present?
        params[:token] && redis_exists(params[:token])
      else
        params[:mobile].present?
      end
    end

    def api_signed_in
      error! I18n.t('please_sign_in') unless api_authentication_token_valid?
    end

    def api_current_user
      if params[:token].present?
        user_id = redis_get(params[:token])
        User.select(:id, :name, :mobile).find_by(id: user_id)
      else
        get_information_clerk_by(mobile: params[:mobile])
      end
    end

    def get_information_clerk_by(*args)
      User.select(:id, :name, :mobile).find_by(*args,
                                              user_type: USER_TYPE["信息录入员"])
    end

    def generate_authentication_token
      SecureRandom.uuid.gsub(/\-/,'')
    end
end